package it.maggioni.sandbox.hibernate.actions;

import it.maggioni.sandbox.hibernate.dto.UserDetails02;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import com.opensymphony.xwork2.Action;

public class Ex02 implements Action {
	
	private String outMsg = "Vedi catalina.out e database";

	@Override
	public String execute() {
		UserDetails02 userDetails = new UserDetails02();
		userDetails.setUserId(1);
		userDetails.setUserName("First User");

		Configuration configuration = new Configuration().configure("/hibernate-02.cfg.xml");
	    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
	    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	    
	    Session session = sessionFactory.openSession();
	    session.beginTransaction();
	    session.save(userDetails);
	    session.getTransaction().commit();
	    session.close();
	    
	    sessionFactory.close();
		
		return SUCCESS;
	}
	
	public static void main(String[] args) {
		Ex02 main = new Ex02();
		main.execute();
	}

	public String getOutMsg() {
		return outMsg;
	}

	public void setOutMsg(String outMsg) {
		this.outMsg = outMsg;
	}

}
